﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;
using System.Data;
using System.Configuration;
using System.IO;
using System.Text;
using System.Linq;

using Wind.Utils;
using Wind.Utils.DataAccess;
using Wind.Framework;
using Wind.Framework.Config;
using Wind.Framework.Entity;
using Wind.MultimediaStation.WebService.Entity;
using Wind.MultimediaStation.Common;
using Wind.Speed;
using WUDS.Client;
using Dundas.Charting.WebControl;
using System.Drawing.Imaging;

namespace Wind.MultimediaStation.WebService
{
    public class CommonBusiness
    {
        private const string SP_GetPlayOrderActsListByOrderID = "SP_MultimediaStation_GetPlayOrderActsListByOrderID";
        private const string SP_GetPlayOrderMaterialListByOrderID = "SP_MultimediaStation_GetPlayOrderMaterialListByOrderID";
        private const string SP_GetPlayOrderActDownInfListByOrderID = "SP_MultimediaStation_GetPlayOrderActDownInfListByOrderID";

        private static IDBHelper _dbHelper = DBFactoryHelper.GetDatabase(DatabaseType.SqlServer, FrameworkSection.GetConnectionString("ConnectionString"));

        /// <summary>
        /// 节目信息
        /// </summary>
        /// <param name="orderID">串联单号</param>
        /// <returns>节目信息</returns>
        public static List<OActInfo> QueryActInfoByOrderID(int orderID)
        {
            try
            {
                string sUrl = "http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port.ToString() + "/MultimediaStation/ClientApplication";
                List<OActInfo> data = new List<OActInfo>();
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderActsListByOrderID, ht);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        OActInfo info = new OActInfo();
                        info.ActID = ParseHelper.Parse<int>(dr["ActID"]);
                        info.ActName = dr["ActName"].ToString();
                        info.ActPlayLength = ParseHelper.Parse<float>(dr["ActPlayLength"]) * 60;
                        info.RefresDataInterval = ParseHelper.Parse<float>(dr["RefreshActInterval"]) * 60;
                        info.ApplicationSWF = dr["ApplicationSWF"].ToString();
                        info.TemplateType = ParseHelper.Parse<int>(dr["TemplateType"]);
                        //
                        if (info.TemplateType == (int)TemplateType.Chart)//单个分时图
                        {
                            List<StockQuote> lstData = QueryMaterialChartInfoListByActID(orderID, info.ActID);
                            if (lstData != null && lstData.Count > 0)
                            {
                                DrawRealTimeChart DrawRealTimeChart = new DrawRealTimeChart();
                                StockQuote StockQuote = lstData[0];

                                ////临时数据
                                //if (StockQuote.QuoteDateList.Count > 0)
                                //{
                                //    DateTime QuoteDateMin = StockQuote.QuoteDateList.Min();
                                //    DateTime QuoteDateMax = StockQuote.QuoteDateList.Max();

                                //    DateTime minDateTime = new DateTime(QuoteDateMin.Year, QuoteDateMin.Month, QuoteDateMin.Day, 9, 30, 0);
                                //    DateTime maxDateTime = new DateTime(QuoteDateMax.Year, QuoteDateMax.Month, QuoteDateMax.Day, 15, 0, 0);
                                //    DateTime PauseStartDateTime = new DateTime(QuoteDateMin.Year, QuoteDateMin.Month, QuoteDateMin.Day, 11, 30, 0);
                                //    DateTime PauseEndDateTime = new DateTime(QuoteDateMax.Year, QuoteDateMax.Month, QuoteDateMax.Day, 13, 0, 0);
                                //    StockQuote.QuoteStartTime = minDateTime;
                                //    StockQuote.QuoteEndTime = maxDateTime;
                                //    StockQuote.PauseStartTime = PauseStartDateTime;
                                //    StockQuote.PauseEndTime = PauseEndDateTime;
                                //}

                                using (Chart myChart = DrawRealTimeChart.GetChart(StockQuote))
                                {
                                    string picName = "DefaultChart.png";
                                    string fileName = string.Format("{0}Picture\\{1}", Utils.EnvironmentHelper.PhyAppPath, picName);

                                    MemoryStream stream = new MemoryStream();
                                    //myChart.Save(stream, ChartImageFormat.Jpeg);
                                    myChart.Save(fileName, ChartImageFormat.Jpeg);

                                    byte[] mydata = new byte[stream.Length];
                                    mydata = stream.ToArray();
                                    stream.Close();

                                    info.ApplicationSWF = Convert.ToBase64String(mydata);
                                }
                            }

                        }
                        else if (info.TemplateType == (int)TemplateType.CompareChart)//对比分时图
                        {
                            List<StockQuote> lstData = QueryMaterialChartInfoListByActID(orderID, info.ActID);
                            if (lstData != null && lstData.Count > 0)
                            {
                                StockQuote StockQuote1 = lstData[0];
                                StockQuote StockQuote2 = lstData[1];
                                DrawCompareChart DrawCompareChart = new DrawCompareChart();
                                using (Chart myChart = DrawCompareChart.GetChart(StockQuote1, StockQuote2))
                                {
                                    string picName = "CompareChart.png";
                                    string fileName = string.Format("{0}Picture\\{1}", Utils.EnvironmentHelper.PhyAppPath, picName);

                                    MemoryStream stream = new MemoryStream();
                                    //myChart.Save(stream, ChartImageFormat.Jpeg);
                                    myChart.Save(fileName, ChartImageFormat.Jpeg);
                                    byte[] mydata = new byte[stream.Length];
                                    mydata = stream.ToArray();
                                    stream.Close();

                                    info.ApplicationSWF = Convert.ToBase64String(mydata);
                                }
                            }
                        }
                        else if (info.TemplateType == (int)TemplateType.OrderUpDown)//涨跌排行
                        {
                            info.MaterialList = QueryMaterialUpDownInfoListByActID(orderID, info.ActID);

                        }
                        else if (info.TemplateType == (int)TemplateType.Video)//视频
                        {
                            info.MaterialList = QueryMaterialInfoListByActIDForVideo(orderID, info.ActID);
                        }
                        else  //普通，图文,分时图
                        {
                            info.MaterialList = QueryMaterialInfoListByActID(orderID, info.ActID, info.TemplateType);
                        }
                        data.Add(info);
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryActInfoByOrderID Exception:", ex);
                throw;
            }
        }




        /// <summary>
        /// 节目素材
        /// </summary>
        /// <param name="orderID">串联单ID</param>
        /// <param name="actID">节目ID</param>
        /// <returns>节目素材</returns>
        public static List<StockQuote> QueryMaterialChartInfoListByActID(int orderID, int actID)
        {
            try
            {
                List<StockQuote> data = new List<StockQuote>();
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                ht.Add("@ActID", actID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderMaterialListByOrderID, ht);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        OMaterialInfo info = new OMaterialInfo();
                        info.MaterialID = ParseHelper.Parse<int>(dr["MaterialID"]);
                        info.MaterialName = dr["MaterialName"].ToString();
                        info.MaterialCode = dr["MaterialCode"].ToString();
                        info.MaterialType = (int)(MaterialType)ParseHelper.Parse<int>(dr["MaterialType"]);
                        //分时图
                        StockQuote quote = MultimediaStationChartBusiness.QueryMaterialStockQuoteListByWindcode(info.MaterialCode);
                        if (quote != null)
                        {
                            quote.ShortName = info.MaterialName;
                            data.Add(quote);
                        }
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryMaterialInfoListByActID Exception:", ex);
                throw;
            }
        }
        /// <summary>
        /// 节目素材
        /// </summary>
        /// <param name="orderID">串联单ID</param>
        /// <param name="actID">节目ID</param>
        /// <returns>节目素材</returns>
        public static List<OMaterialInfo> QueryMaterialInfoListByActID(int orderID, int actID,int templateType)
        {
            try
            {
                List<OMaterialInfo> data = new List<OMaterialInfo>();
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                ht.Add("@ActID", actID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderMaterialListByOrderID, ht);
                if (dt != null && dt.Rows.Count > 0)
                {
                    int iRow = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        OMaterialInfo info = new OMaterialInfo();
                        info.MaterialID = ParseHelper.Parse<int>(dr["MaterialID"]);
                        info.MaterialName = dr["MaterialName"].ToString();
                        info.MaterialCode = dr["MaterialCode"].ToString();
                        info.MaterialType = (int)(MaterialType)ParseHelper.Parse<int>(dr["MaterialType"]);
                        if (templateType == (int)TemplateType.WindCode)
                        {
                            info = new MultimediaStationWindMarketBusiness().QuerySpeedSharpByMaterialCode(info);
                        }
                        else if (templateType == (int)TemplateType.News)
                        {
                            info = new MultimediaStationNewsBusiness().QueryByMaterialCode(info, "Wind金融屏", iRow);//"ON06");
                            iRow++;
                        }
                        else if (templateType == (int)TemplateType.PicNews)
                        {
                            info = new MultimediaStationNewsBusiness().QueryByMaterialCode(info, "图片新闻", iRow);
                            if (info != null)
                            {
                                if (info.MaterialName.Length > 256)
                                {
                                    info.MaterialName = info.MaterialName.Substring(0, 256);
                                }
                                info.MaterialName = "news/"
                                                    + info.MaterialName.Replace("\\", "_")
                                                     .Replace("/", "_").Replace(":", "_").Replace("*", "_").Replace("?", "_")
                                                     .Replace("\"", "_").Replace("<", "_").Replace(">", "_").Replace("|", "_");
                            }
                            iRow++;
                        }
                        if (info != null)
                        {
                            data.Add(info);
                        }
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryMaterialInfoListByActID Exception:", new Exception("orderID:" + orderID + ";actID:" + actID.ToString() + ex.Message.ToString()));
                throw;
            }
        }

        /// <summary>
        /// 节目素材
        /// </summary>
        /// <param name="orderID">串联单ID</param>
        /// <param name="actID">节目ID</param>
        /// <returns>节目素材</returns>
        public static List<OMaterialInfo> QueryMaterialPictureListByActID(int orderID, int actID)
        {
            try
            {
                List<OMaterialInfo> data = new List<OMaterialInfo>();
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                ht.Add("@ActID", actID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderMaterialListByOrderID, ht);
                if (dt != null && dt.Rows.Count > 0)
                {
                    int iRow = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        OMaterialInfo info = new OMaterialInfo();
                        info.MaterialType = (int)(MaterialType)ParseHelper.Parse<int>(dr["MaterialType"]);

                        info = new MultimediaStationNewsBusiness().QueryByMaterialCode(info, "图片新闻", iRow);
                        iRow++;
                        if (info != null && !string.IsNullOrEmpty(info.MaterialName))
                        {
                            data.Add(info);
                        }
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryMaterialInfoListByActID Exception:", ex);
                return null;
            }
        }
        /// <summary>
        /// 涨跌幅排行榜10条记录
        /// </summary>
        /// <param name="orderID">串联单ID</param>
        /// <param name="actID">素材ID</param>
        /// <returns>涨跌幅排行榜10条记录</returns>
        public static List<OMaterialInfo> QueryMaterialUpDownInfoListByActID(int orderID, int actID)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                ht.Add("@ActID", actID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderMaterialListByOrderID, ht);
                string strMaterialCode = string.Empty;
                if (dt != null && dt.Rows.Count > 0)
                    strMaterialCode = dt.Rows[0]["MaterialCode"].ToString();
                if (strMaterialCode == "")

                    return null;
                List<OMaterialInfo> data = new List<OMaterialInfo>();
                SpeedSharpChartData sscd = new MultimediaStationSpeedSharpBusiness().GetSpeedSharpChartData(strMaterialCode, 5, 5);
                //前5名
                foreach (SpeedSharpChartDataItem item in sscd.TopNData)
                {
                    OMaterialInfo info = new OMaterialInfo();
                    info.MaterialCode = item.WindCode;
                    info.MaterialName = CloudManager.GetInfoNameByWindCode(info.MaterialCode);
                    info.MaterialTime = FormartString(item.TradeTime.ToString());
                    info.MaterialValue =  string.Format("{0:0.00}", item.NewPrice.ToString());
                    info.UpDownValue = string.Format("{0:0.00}",item.Range.ToString());
                    info.UpDownPercent = "+" + string.Format("{0:0.00}", item.RangePercentage * 100) + "%";
                    data.Add(info);
                }
                //后5名
                foreach (SpeedSharpChartDataItem item in sscd.BottomNData)
                {
                    OMaterialInfo info = new OMaterialInfo();
                    info.MaterialCode = item.WindCode;
                    info.MaterialName = CloudManager.GetInfoNameByWindCode(info.MaterialCode);
                    info.MaterialTime = FormartString(item.TradeTime.ToString());
                    info.MaterialValue = string.Format("{0:0.00}",item.NewPrice.ToString());
                    info.UpDownValue = string.Format("{0:0.00}",item.Range.ToString());
                    info.UpDownPercent = string.Format("{0:0.00}", item.RangePercentage * 100) + "%";
                    data.Add(info);
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryMaterialUpDownInfoListByActID Exception:", ex);
                throw;
            }
        }
        /// <summary>
        /// 节目素材
        /// </summary>
        /// <param name="orderID">串联单ID</param>
        /// <param name="actID">节目ID</param>
        /// <returns>节目素材</returns>
        public static List<OMaterialInfo> QueryMaterialInfoListByActIDForVideo(int orderID, int actID)
        {
            try
            {
                List<OMaterialInfo> data = new List<OMaterialInfo>();
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                ht.Add("@ActID", actID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderMaterialListByOrderID, ht);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        OMaterialInfo info = new OMaterialInfo();
                        info.MaterialID = ParseHelper.Parse<int>(dr["MaterialID"]);
                        info.MaterialName = dr["MaterialName"].ToString();
                        info.MaterialCode = dr["MaterialCode"].ToString();
                        info.MaterialType = (int)(MaterialType)ParseHelper.Parse<int>(dr["MaterialType"]);
                        info.MaterialValue = "UploadFiles/" + dr["DownloadUrl"].ToString();
                        data.Add(info);
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryMaterialInfoListByActID Exception:", ex);
                throw;
            }
        }
        /// <summary>
        /// 串联单素材
        /// </summary>
        /// <param name="orderID">单号</param>
        /// <returns>串联单素材</returns>
        public static List<OActDownInfo> QueryActDownInfByOrderID(int orderID)
        {
            try
            {
                List<OActDownInfo> data = new List<OActDownInfo>();
                Hashtable ht = new Hashtable();
                ht.Add("@OrderID", orderID);
                DataTable dt = _dbHelper.ExcuteDataTable(SP_GetPlayOrderActDownInfListByOrderID, ht);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        OActDownInfo info = new OActDownInfo();
                        info.DownloadTime = ParseHelper.Parse<int>(dr["DownloadBeforeTime"]) * 60;
                        info.DownloadURL = dr["DownloadURL"].ToString();
                        info.DownloadType = ParseHelper.Parse<int>(dr["DownloadType"]);
                        data.Add(info);
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationService QueryActDownInfByOrderID Exception:", ex);
                return null;
            }
        }
        private static string FormartString(string strTradeTime)
        {
            strTradeTime = strTradeTime.PadLeft(6, '0');
            return strTradeTime.Substring(0, 2) + ":" + strTradeTime.Substring(2, 2) + ":" + strTradeTime.Substring(4, 2);
        }
    }
    /// <summary>
    /// CloudManager
    /// </summary>
    public class CloudManager
    {
        public static string GetInfoNameByWindCode(string windCode)
        {
            try
            {
                string command = string.Format("function name=b_info_name windCode=[{0}]", windCode);
                WUDS.Client.WUDSReport report = Wind.BaseService.CloudManager.GetCloudFunction(command, "");
                return (report.Columns[0] as WUDSReportColumn<string>).Values[0];
            }
            catch (Exception ex)
            {
                LogHelper.Write("CloudManager GetInfoNameByWindCode Exception:", ex);
                return "";
            }
        }
    }
}
